package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.YawWindowData;
import com.ironman.common.params.YawParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class YawPostHandler extends BasePostHandler<YawWindowData> {

    private Double preYaw = null;

    private final YawParam yawParam;

    public YawPostHandler(YawParam yawParam) {
        this.yawParam = yawParam;
    }

    @Override
    public void handler(YawWindowData data, Consumer<YawWindowData> consumer) {
        doHandler(data, consumer);
    }

    @Override
    public void threshold(YawWindowData data) {
        Double yaw = data.getYaw();
        if (Objects.isNull(yaw)) {
            return;
        }

        if (preYaw == null) {
            getCounter().incrementAndGet();
            preYaw = yaw;
            return;
        }

        Integer yawThreshold = yawParam.getYawThreshold();
        double diff = Math.abs(yaw - preYaw);
        diff = diff > 180 ? 360 - diff : diff;
        if (diff > yawThreshold) {
            getCounter().set(0);
            log.debug("船首向触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", yawThreshold, yaw, preYaw, diff);
            preYaw = yaw;
        }

        Integer countThreshold = yawParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.debug("船首向触发数量阈值:{} ", countThreshold);
            preYaw = yaw;
            return;
        }
        data.setYaw(preYaw);
    }

}
